package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.user.UserMapper;
import com.sky.mapper.user.UserVoMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserVoMapper,UserLoginVO> implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final JwtProperties jwtProperties;
    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;
//    private final RedisTemplate<String,Object> redisTemplate;
    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) throws LoginException {

        Map<String, Object> claims = new HashMap<>();

        Map<String, String> query = new HashMap<>();
        //获取openid
        query.put("appid",weChatProperties.getAppid()); //微信公众号appid
        query.put("secret",weChatProperties.getSecret()); //微信公众号app secret
        query.put("js_code",userLoginDTO.getCode()); //微信返回的临时登录凭证code
        query.put("grant_type","authorization_code"); //固定值
        String json = HttpClientUtil.doGet(WX_LOGIN, query);
        String openid = JSON.parseObject(json).getString("openid");

        //判断openid是否为空选择是否需要添加新用户
        if (openid == null) {
            throw new LoginException(MessageConstant.LOGIN_FAILED);
        }
        //查询redis中是否存在user
//        if (redisTemplate.opsForValue().get("userLoginVO") != null){
//            return redisTemplate.opsForValue().get("userLoginVO");
//        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("openid", openid));
        if (user == null){
            user = User.builder()
                    .createTime(LocalDateTime.now())
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }

        //创建jwt令牌
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey()
                                        ,jwtProperties.getUserTtl()
                                        ,claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();
//        redisTemplate.opsForValue().set("userLoginVO",userLoginVO);

        //返回用户信息
        return userLoginVO;
    }
}
